/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lucky.blessing.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lucky.blessing.DemoHelper;
import com.lucky.blessing.R;
import com.lucky.blessing.data.result.SmsCode;
import com.lucky.blessing.network.AppNetworkUtils;
import com.lucky.blessing.network.NetworkResultUtils;
import com.lucky.blessing.utils.AccountValidatorUtil;
import com.lucky.blessing.utils.QiniuUtils;
import com.lucky.blessing.utils.UserInfoUtils;
import com.mathum.baseapp.callback.UpLoadImgCallback;
import com.mathum.baseapp.data.BaseData;
import com.mathum.baseapp.data.BaseDialogData;
import com.mathum.baseapp.network.NetworkCallback;
import com.mathum.baseapp.network.NetworkUtils;
import com.mathum.baseapp.widget.RecyclerViewDialog;

import java.util.ArrayList;
import java.util.List;

import cn.com.mathum.gallerylib.BastiGallery;

/**
 * register screen
 */
public class RegisterNicknameActivity extends BaseActivity {
    private static final String TAG = "RNickActivity";
    private ImageView userAvatarImage;
    private EditText userNickEditText;
    private Button registernickBtn;
    private String userMobile;
    private String userCodeMsg;
    private String userName;
    private String userPassword;
    private String userNickName;
    private String userAvatarString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.em_activity_register_nickname);
        userAvatarImage = (ImageView) findViewById(R.id.userAvatarImage);
        userNickEditText = (EditText) findViewById(R.id.usernick);
        registernickBtn = (Button) findViewById(R.id.registernickBtn);
        userMobile=getIntent().getStringExtra("user_mobile");
        userCodeMsg=getIntent().getStringExtra("user_msgcode");
        userName=getIntent().getStringExtra("user_name");
        userPassword=getIntent().getStringExtra("user_password");
        userNickName=getIntent().getStringExtra("userNickName");
        userAvatarImage.setOnClickListener(view -> {
//            Toast.makeText(RegisterNicknameActivity.this, "头像点击", Toast.LENGTH_LONG).show();
            showSelectPhotoDialog();
        });
        if(userNickName!=null){
            userNickEditText.setText(userNickName);
            registernickBtn.setText("设置");
            userAvatarImage.setImageResource(R.drawable.ic_launcher);
            userAvatarString=UserInfoUtils.getAppUserUrl(this);
            Log.d("getImageAvatarString",userAvatarString);
            if(userAvatarString.startsWith("http://qiniu.500-china.com/")){
                Glide.with(RegisterNicknameActivity.this).load(userAvatarString).into(userAvatarImage);
            }
        }
    }

    /**
     * 弹出选择照片的对话框
     */
    private void showSelectPhotoDialog() {
        List<BaseDialogData> baseDataList = new ArrayList<>();
        baseDataList.add(new BaseDialogData("相机", 0));
        baseDataList.add(new BaseDialogData("图片", 1));
        RecyclerViewDialog recyclerViewDialog = RecyclerViewDialog.getInstance(baseDataList);
        recyclerViewDialog.show(getSupportFragmentManager(), "");
        recyclerViewDialog.setOnItemClickListener((position1, view1) -> {
            if (position1 >= 0 && position1 < baseDataList.size()) {
                BaseDialogData baseDialogData = baseDataList.get(position1);
                switch (baseDialogData.getId()) {
                    case 0:
                        BastiGallery.openCamera(RegisterNicknameActivity.this, baseDialogData.getId());
                        break;
                    case 1:
                        BastiGallery.openGallery(RegisterNicknameActivity.this, baseDialogData.getId());
                        break;
                }
                recyclerViewDialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            //相机
            String url = BastiGallery.getmCurrentPhotoPath();
            String fileName = BastiGallery.getPathFromCamera(data, url);
            byte[] img = BastiGallery.Bitmap2Bytes(BastiGallery.getimage(fileName));
            upLoadFeedBackImg(img);
        } else if (requestCode == 1) {
            String fileName = BastiGallery.getPathFromGallery(this, data);
            if (TextUtils.isEmpty(fileName)) {
                Toast.makeText(RegisterNicknameActivity.this, "相册异常", Toast.LENGTH_LONG).show();
                return;
            }
            byte[] img = BastiGallery.Bitmap2Bytes(BastiGallery.getimage(fileName));
            upLoadFeedBackImg(img);
        }
    }

    private void upLoadFeedBackImg(byte[] img) {
        final ProgressDialog pd = new ProgressDialog(RegisterNicknameActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d(TAG, "EMClient.getInstance().onCancel");
            }
        });
        pd.setMessage("正在上传");
        pd.show();
        QiniuUtils.getUploadManagerInstance();
        //已经上传过的不上传
        QiniuUtils.uploadImg(this, img, QiniuUtils.createImageKey(UserInfoUtils.getPhone(this)), new UpLoadImgCallback() {
            @Override
            public void onSuccess(String imgUrl) {
                pd.dismiss();
                Log.e("111111111111", "imgUrl = " + imgUrl);
                userAvatarString=imgUrl;
                Glide.with(RegisterNicknameActivity.this).load(imgUrl).into(userAvatarImage);
            }

            @Override
            public void onFailure() {
                pd.dismiss();
            }
        });
    }

    public void register(View view) {
        final String usernick = userNickEditText.getText().toString().trim();
        if (TextUtils.isEmpty(usernick)) {
            Toast.makeText(this, getResources().getString(R.string.User_name_cannot_be_empty), Toast.LENGTH_SHORT).show();
            userNickEditText.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(userAvatarString)) {
            Toast.makeText(this, "请选择您的用户头像", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(usernick)) {
            final ProgressDialog pd = new ProgressDialog(this);
            if(userNickName!=null&&userAvatarString!=null){
                pd.setMessage("正在处理，请稍后...");
                pd.show();

                //注册
                NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().updatenickname(UserInfoUtils.getAppUserId(RegisterNicknameActivity.this),usernick,userAvatarString),
                        new NetworkCallback<BaseData>() {
                            @Override
                            public void onSuccess(BaseData baseData) {
                                if (!NetworkResultUtils.isSuccess(baseData)) {
                                    pd.dismiss();
                                    Toast.makeText(RegisterNicknameActivity.this, baseData.getInfo(), Toast.LENGTH_LONG).show();
                                    return;
                                }
                                if (!RegisterNicknameActivity.this.isFinishing()){
                                    pd.dismiss();
                                }
                                UserInfoUtils.setNikeName(usernick,RegisterNicknameActivity.this);
                                UserInfoUtils.setAppUserUrl(userAvatarString,RegisterNicknameActivity.this);
                                Toast.makeText(getApplicationContext(), "个人资料修改成功", Toast.LENGTH_SHORT).show();
                                finish();
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                pd.dismiss();
                                Toast.makeText(RegisterNicknameActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        });
            }else{



            pd.setMessage(getResources().getString(R.string.Is_the_registered));
            pd.show();

            //注册
            NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().register1(userMobile, userName, userPassword, usernick,userCodeMsg,userAvatarString),
                    new NetworkCallback<BaseData>() {
                        @Override
                        public void onSuccess(BaseData baseData) {
                            if (!NetworkResultUtils.isSuccess(baseData)) {
                                pd.dismiss();
                                Toast.makeText(RegisterNicknameActivity.this, baseData.getInfo(), Toast.LENGTH_LONG).show();
                                return;
                            }
                            if (!RegisterNicknameActivity.this.isFinishing())
                                pd.dismiss();

                            DemoHelper.getInstance().setCurrentUserName(userName);
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
                            setResult(Activity.RESULT_OK, getIntent());
                            finish();

                        }

                        @Override
                        public void onFailure(Throwable t) {
                            pd.dismiss();
                            Toast.makeText(RegisterNicknameActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });

            }
        }
    }

    public void back(View view) {
        finish();
    }

}
